package base

import (
	"encoding/json"
	"fmt"
	"github.com/chanxuehong/wechat/mp/core"
	"github.com/chanxuehong/wechat/mp/message/template"
	"log"
)

type WxOpera struct {
	appID       string
	appSecret   string
	openID      string
	templateID  string
	accessToken string
	msgID       string
	data        string

	client *core.Client
}

func NowWxOpera(appID, appSecret string) *WxOpera {
	srv := &WxOpera{
		appID:     appID,
		appSecret: appSecret,
	}

	tokenServer := core.NewDefaultAccessTokenServer(appID, appSecret, nil)
	accessToken, err := tokenServer.Token()
	if err != nil {
		log.Fatal("获取 AccessToken 失败:", err)
		return nil
	}
	srv.accessToken = accessToken
	srv.client = core.NewClient(tokenServer, nil)
	return srv
}

func (this *WxOpera) WxTokenServerClient(openID, templateID, data string) (int64, error) {
	msg := &template.TemplateMessage{
		ToUser:     openID,
		TemplateId: templateID,
		Data:       json.RawMessage(data),
	}
	// 发送模板消息
	msgID, err := template.Send(this.client, msg)
	if err != nil {
		//log.Fatal("发送模板消息失败:", err)
		return -1, fmt.Errorf("发送模板消息失败:%s", err.Error())
	}
	return msgID, nil
}
